package com.lzc.controller;

import cn.hutool.core.lang.UUID;
import com.lzc.pojo.vo.Result;
import com.lzc.pojo.vo.UserLoginVo;
import com.lzc.pojo.vo.UserRegisterVo;
import com.lzc.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@RequestMapping("/im/login")
public class LoginController {

    @Autowired
    private LoginService loginService;

    /**
     * 系统用户登陆
     * @param userLoginVo 登陆信息
     * @return
     */
    @PostMapping("/")
    @ResponseBody
    public Result loginUser(@RequestBody UserLoginVo userLoginVo){

        return loginService.loginSysUser(userLoginVo);

    }

    /**
     * 系统用户注册
     * @param userRegisterVo 注册信息
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public Result registerUser(@RequestBody UserRegisterVo userRegisterVo){

        return loginService.registerSysUser(userRegisterVo);

    }


    /**
     * 获取二维码需要的uuid
     * @return
     */
    @GetMapping("/uuid")
    @ResponseBody
    public Result getUuid(){
        // 生成uuid
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString().replace("-", "");
        return Result.OK(uuidStr);
    }


    @GetMapping("/wx/{uuid}")
    public void wxLoginCode(@PathVariable("uuid") String uuid,HttpServletResponse response){
        // 返回包含uuid参数的二维码
        try {
            loginService.createWxLoginCode(uuid,response);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 微信回调
     * @param code
     * @param uuid 二维码中的uuid
     */
    @RequestMapping("/wx/callBack")
    public void wxCallBack(@RequestParam("code") String code,
                           @RequestParam("state")String uuid){

        // 根据code获取用户信息
        loginService.loginWxUser(code,uuid);

    }

    /**
     * 浏览器拿uuid来换取jwt令牌
     * @param uuid
     * @return
     */
    @PostMapping("/getJwt")
    @ResponseBody
    public Result getJWT(@RequestParam("uuid") String uuid){

        return loginService.getJwt(uuid);

    }

}
